package mk.jug.academy.service;

import java.util.List;

import mk.jug.academy.dao.CommentDAO;
import mk.jug.academy.dao.ContentDAO;
import mk.jug.academy.model.Comment;
import mk.jug.academy.model.CommentStatus;
import mk.jug.academy.model.Content;
import mk.jug.academy.model.Page;
import mk.jug.academy.preconditions.CommentPreconditions;
import mk.jug.academy.util.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Contains the business logic implementation for the {@link CommentService}.
 *
 * @author Ice.Penov
 */
@Service
public class CommentServiceImpl implements CommentService {

	@Autowired private CommentDAO commentDAO;
	@Autowired private ContentDAO contentDAO;
		
	@Override
	public List<Comment> fetchCommentsForContent(Content content) {
		return commentDAO.findByContent(content.getId());
	}

	@Override
	public Page<Comment> listActive(int pageNumber, int itemsPerPage) {
		return commentDAO.findByStatus(CommentStatus.PUBLISHED, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}
	
	@Override
	public Page<Comment> listDeleted(int pageNumber, int itemsPerPage) {
		return commentDAO.findByStatus(CommentStatus.DELETED, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}

	@Override @Transactional
	public void add(Comment comment, Content content) {
		CommentPreconditions.add(comment, content);
		comment.setContentID(content.getId());
		content.increaseNumberOfComments();
		commentDAO.save(comment);
		contentDAO.save(content);
	}
	
	@Override @Transactional
	public void delete(Comment comment) {
		CommentPreconditions.delete(comment);
		comment.setStatus(CommentStatus.DELETED);
		Content content = contentDAO.find(Content.class, comment.getContentID());
		content.decreaseNumberOfComments();
		commentDAO.save(comment);
		contentDAO.save(content);		
	}
	
}